import { JobInfo, PluginSettings, DeliveryRecord } from '@/types';
import { addDeliveryRecord, incrementTodayCount } from '@/utils/storage';

class BossAutoDelivery {
  private isRunning = false;
  private isPaused = false;
  private settings: PluginSettings | null = null;
  private deliveredJobs = new Set<string>();
  private currentJobIndex = 0;
  private scrollPosition = 0;

  constructor() {
    this.init();
  }

  private init() {
    console.log('Content script 开始初始化...');
    console.log('当前页面URL:', window.location.href);
    
    // 监听来自popup的消息
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      console.log('收到消息:', message);
      
      switch (message.action) {
        case 'START_DELIVERY':
          console.log('开始投递消息，设置:', message.settings);
          this.startDelivery(message.settings);
          break;
        case 'PAUSE_DELIVERY':
          this.pauseDelivery();
          break;
        case 'RESUME_DELIVERY':
          this.resumeDelivery();
          break;
        case 'STOP_DELIVERY':
          this.stopDelivery();
          break;
      }
      sendResponse({ success: true });
      return true; // 保持消息通道开放
    });

    // 页面加载完成后检查是否为Boss直聘页面
    if (this.isBossPage()) {
      this.injectStyles();
      console.log('Boss直聘自动投递插件已加载');
      
      // 添加页面就绪检测
      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
          console.log('DOM内容加载完成');
          this.checkPageElements();
        });
      } else {
        console.log('页面已完全加载');
        this.checkPageElements();
      }
    } else {
      console.log('当前页面不是Boss直聘页面');
    }
  }

  // 检查页面元素
  private checkPageElements() {
    console.log('检查页面元素...');
    const jobCards = document.querySelectorAll('.job-card-wrap');
    const jobBoxes = document.querySelectorAll('.job-card-box');
    const cardAreas = document.querySelectorAll('.card-area');
    
    console.log('页面元素统计:', {
      'job-card-wrap': jobCards.length,
      'job-card-box': jobBoxes.length,
      'card-area': cardAreas.length
    });
    
    if (jobCards.length > 0) {
      console.log('找到职位卡片，插件准备就绪');
    } else {
      console.log('未找到职位卡片，可能需要等待页面加载或选择器不正确');
    }
  }

  // 检查是否为Boss直聘页面
  private isBossPage(): boolean {
    return window.location.hostname.includes('zhipin.com');
  }

  // 注入样式
  private injectStyles() {
    const style = document.createElement('style');
    style.textContent = `
      .boss-auto-delivery-highlight {
        border: 2px solid #00D4AA !important;
        box-shadow: 0 0 10px rgba(0, 212, 170, 0.3) !important;
      }
      .boss-auto-delivery-processing {
        opacity: 0.6 !important;
        pointer-events: none !important;
      }
      .boss-auto-delivery-processed {
        position: relative;
        opacity: 0.7 !important;
      }
      .boss-auto-delivery-processed::after {
        content: "已处理";
        position: absolute;
        top: 5px;
        right: 5px;
        background: #10b981;
        color: white;
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 12px;
        z-index: 1000;
      }
      .boss-auto-delivery-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        background: #00D4AA;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        z-index: 10000;
        font-size: 14px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    `;
    document.head.appendChild(style);
  }

  // 标记职位卡片为已处理
  private markJobCardAsProcessed(jobCard: HTMLElement) {
    jobCard.classList.add('boss-auto-delivery-processed');
    console.log('职位卡片已标记为已处理');
  }

  // 开始投递
  private async startDelivery(settings: PluginSettings) {
    this.settings = settings;
    this.isRunning = true;
    this.isPaused = false;
    
    console.log('开始投递，设置:', settings);
    this.showToast('开始自动投递...');
    
    try {
      await this.processCurrentPage();
    } catch (error) {
      console.error('投递过程中出错:', error);
      this.showToast('投递过程中出现错误', 'error');
    }
  }

  // 暂停投递
  private pauseDelivery() {
    this.isPaused = true;
    this.showToast('投递已暂停');
  }

  // 恢复投递
  private resumeDelivery() {
    this.isPaused = false;
    this.showToast('投递已恢复');
    this.processCurrentPage();
  }

  // 停止投递
  private stopDelivery() {
    this.isRunning = false;
    this.isPaused = false;
    this.showToast('投递已停止');
  }

  // 处理当前页面
  private async processCurrentPage() {
    if (!this.isRunning || this.isPaused || !this.settings) return;

    const jobs = this.extractJobsFromPage();
    console.log(`找到 ${jobs.length} 个职位`);

    for (let i = this.currentJobIndex; i < jobs.length; i++) {
      if (!this.isRunning || this.isPaused) break;

      const job = jobs[i];
      this.currentJobIndex = i;

      // 检查是否已投递过
      if (this.deliveredJobs.has(job.id)) {
        console.log(`跳过已投递职位: ${job.title}`);
        continue;
      }

      // 检查职位卡片是否已被标记为已处理
      const jobCard = this.findJobCard(job);
      if (jobCard && jobCard.classList.contains('boss-auto-delivery-processed')) {
        console.log(`跳过已处理职位: ${job.title}`);
        continue;
      }

      // 检查黑名单公司
      if (this.isCompanyBlacklisted(job.company)) {
        console.log(`跳过黑名单公司: ${job.company}`);
        continue;
      }

      // 检查关键词过滤
      if (this.hasFilteredKeywords(job)) {
        console.log(`跳过包含过滤关键词的职位: ${job.title}`);
        continue;
      }

      // 检查今日投递限制（先检查，不增加计数）
      const currentTodayCount = await this.getTodayCount();
      if (currentTodayCount >= this.settings.dailyLimit) {
        this.showToast(`已达今日投递上限 ${this.settings.dailyLimit} 条`, 'warning');
        this.stopDelivery();
        break;
      }

      // 执行投递
      const deliverySuccess = await this.deliverToJob(job);
      
      // 只有投递成功才增加计数
      if (deliverySuccess) {
        await incrementTodayCount();
      }
      
      // 等待间隔时间
      await this.sleep(this.settings.deliveryInterval * 1000);
    }

    // 当前页面处理完成，尝试翻页
    if (this.isRunning && !this.isPaused && this.settings.autoScroll) {
      await this.scrollToNextPage();
    }
  }

  // 获取今日投递数量（不增加计数）
  private async getTodayCount(): Promise<number> {
    const today = new Date().toDateString();
    const result = await chrome.storage.local.get('boss_auto_delivery_daily_count');
    const dailyData = result.boss_auto_delivery_daily_count || {};
    return dailyData[today] || 0;
  }

  // 从页面提取职位信息 - 根据实际Boss直聘HTML结构
  private extractJobsFromPage(): JobInfo[] {
    const jobs: JobInfo[] = [];
    
    console.log('开始提取职位信息...');
    
    // 根据实际HTML结构使用正确的选择器
    const cardAreas = document.querySelectorAll('.card-area');
    console.log(`找到 ${cardAreas.length} 个 .card-area 元素`);
    
    if (cardAreas.length === 0) {
      console.log('未找到 .card-area 元素，尝试其他选择器');
      
      // 备用选择器
      const backupSelectors = [
        '.job-card-wrap',
        '.job-card-box',
        '.job-list-item'
      ];
      
      for (const selector of backupSelectors) {
        const elements = document.querySelectorAll(selector);
        console.log(`尝试选择器 ${selector}，找到 ${elements.length} 个元素`);
        if (elements.length > 0) {
          return this.extractJobsFromElements(elements);
        }
      }
      
      this.showToast('未找到职位信息，请确保页面已完全加载', 'warning');
      return jobs;
    }
    
    // 处理每个 card-area
    cardAreas.forEach((cardArea, index) => {
      try {
        console.log(`处理第 ${index + 1} 个职位卡片区域`);
        
        const jobCardWrap = cardArea.querySelector('.job-card-wrap');
        if (!jobCardWrap) {
          console.log('未找到 .job-card-wrap');
          return;
        }
        
        const titleElement = jobCardWrap.querySelector('.job-name');
        const salaryElement = jobCardWrap.querySelector('.job-salary');
        const companyElement = jobCardWrap.querySelector('.boss-name');
        const locationElement = jobCardWrap.querySelector('.company-location');
        const linkElement = jobCardWrap.querySelector('a[href*="/job_detail/"]');

        // 获取薪资信息 - 处理Boss直聘的反爬虫机制
        let salaryText = '';
        if (salaryElement) {
          // 首先尝试获取计算后的样式文本
          const computedSalary = window.getComputedStyle(salaryElement).getPropertyValue('content');
          if (computedSalary && computedSalary !== 'none' && computedSalary !== '""') {
            salaryText = computedSalary.replace(/['"]/g, '');
          } else {
            // 尝试获取实际显示的文本（通过渲染后的内容）
            const rect = salaryElement.getBoundingClientRect();
            if (rect.width > 0 && rect.height > 0) {
              // 元素可见，尝试获取其显示文本
              salaryText = this.extractVisibleSalary(salaryElement);
            }
            
            // 如果还是获取不到，使用原始文本作为备选
            if (!salaryText || salaryText.includes('·') || salaryText.includes('-K')) {
              salaryText = salaryElement.textContent?.trim() || '';
            }
          }
        }

        console.log('元素查找结果:', {
          title: titleElement?.textContent?.trim(),
          company: companyElement?.textContent?.trim(),
          salary: salaryText,
          salaryRaw: salaryElement?.textContent?.trim(),
          location: locationElement?.textContent?.trim(),
          hasLink: !!linkElement
        });

        if (titleElement && companyElement && linkElement) {
          const job: JobInfo = {
            id: this.generateJobId(jobCardWrap),
            title: titleElement.textContent?.trim() || '',
            company: companyElement.textContent?.trim() || '',
            salary: salaryText || '薪资面议',
            location: locationElement?.textContent?.trim() || '',
            url: (linkElement as HTMLAnchorElement).href || ''
          };
          
          jobs.push(job);
          console.log(`成功提取职位: ${job.title} - ${job.company}`);
        } else {
          console.log('职位元素不完整，跳过');
        }
      } catch (error) {
        console.error('提取职位信息失败:', error);
      }
    });

    console.log(`总共提取到 ${jobs.length} 个有效职位`);
    return jobs;
  }

  // 提取可见的薪资信息（处理反爬虫）
  private extractVisibleSalary(salaryElement: Element): string {
    try {
      // 方法1: 尝试通过伪元素获取
      const beforeContent = window.getComputedStyle(salaryElement, '::before').getPropertyValue('content');
      const afterContent = window.getComputedStyle(salaryElement, '::after').getPropertyValue('content');
      
      if (beforeContent && beforeContent !== 'none' && beforeContent !== '""') {
        return beforeContent.replace(/['"]/g, '');
      }
      
      if (afterContent && afterContent !== 'none' && afterContent !== '""') {
        return afterContent.replace(/['"]/g, '');
      }
      
      // 方法2: 尝试通过子元素获取
      const childElements = salaryElement.querySelectorAll('*');
      for (const child of childElements) {
        const childText = child.textContent?.trim();
        if (childText && childText.match(/\d+[-~]\d+K/)) {
          return childText;
        }
      }
      
      // 方法3: 尝试通过data属性获取
      const dataAttrs = ['data-salary', 'data-price', 'data-range'];
      for (const attr of dataAttrs) {
        const value = salaryElement.getAttribute(attr);
        if (value && value.match(/\d+[-~]\d+K/)) {
          return value;
        }
      }
      
      // 方法4: 返回默认值
      return '薪资面议';
    } catch (error) {
      console.error('提取薪资信息失败:', error);
      return '薪资面议';
    }
  }

  // 从元素列表中提取职位信息（备用方法）
  private extractJobsFromElements(elements: NodeListOf<Element>): JobInfo[] {
    const jobs: JobInfo[] = [];
    
    elements.forEach((element, index) => {
      try {
        console.log(`处理第 ${index + 1} 个职位元素`);
        
        const titleElement = element.querySelector('.job-name');
        const salaryElement = element.querySelector('.job-salary');
        const companyElement = element.querySelector('.boss-name');
        const locationElement = element.querySelector('.company-location');
        const linkElement = element.querySelector('a[href*="/job_detail/"]');

        if (titleElement && companyElement && linkElement) {
          const job: JobInfo = {
            id: this.generateJobId(element),
            title: titleElement.textContent?.trim() || '',
            company: companyElement.textContent?.trim() || '',
            salary: salaryElement?.textContent?.trim() || '薪资面议',
            location: locationElement?.textContent?.trim() || '',
            url: (linkElement as HTMLAnchorElement).href || ''
          };
          
          jobs.push(job);
          console.log(`成功提取职位: ${job.title} - ${job.company}`);
        }
      } catch (error) {
        console.error('提取职位信息失败:', error);
      }
    });

    return jobs;
  }

  // 生成职位ID
  private generateJobId(element: Element): string {
    const linkElement = element.querySelector('a[href*="/job_detail/"]') as HTMLAnchorElement;
    if (linkElement && linkElement.href) {
      const match = linkElement.href.match(/job_detail\/([^?]+)/);
      return match ? match[1] : `job_${Date.now()}_${Math.random()}`;
    }
    return `job_${Date.now()}_${Math.random()}`;
  }

  // 检查公司是否在黑名单中
  private isCompanyBlacklisted(company: string): boolean {
    if (!this.settings?.blacklistCompanies) return false;
    return this.settings.blacklistCompanies.some(blacklisted => 
      company.toLowerCase().indexOf(blacklisted.toLowerCase()) !== -1
    );
  }

  // 检查是否包含过滤关键词
  private hasFilteredKeywords(job: JobInfo): boolean {
    if (!this.settings?.filterKeywords) return false;
    
    const searchText = `${job.title} ${job.company}`.toLowerCase();
    return this.settings.filterKeywords.some(keyword => 
      searchText.indexOf(keyword.toLowerCase()) !== -1
    );
  }

  // 投递职位 - 根据实际HTML结构重新设计
  private async deliverToJob(job: JobInfo): Promise<boolean> {
    let jobCard: HTMLElement | null = null;
    
    try {
      console.log(`\n=== 开始处理职位 ===`);
      console.log(`目标职位: ${job.title}`);
      console.log(`目标公司: ${job.company}`);
      console.log(`职位ID: ${job.id}`);
      
      this.showToast(`正在投递: ${job.title}`);
      
      // 第一步：找到职位卡片
      jobCard = this.findJobCard(job);
      if (!jobCard) {
        console.error(`❌ 未找到职位卡片: ${job.title} - ${job.company}`);
        throw new Error('未找到职位卡片');
      }

      console.log(`✅ 找到职位卡片: ${job.title} - ${job.company}`);
      
      // 高亮显示当前处理的职位
      jobCard.classList.add('boss-auto-delivery-highlight');
      
      // 第二步：正确点击职位卡片，触发Boss直聘的事件处理器
      console.log(`🖱️ 准备点击职位卡片: ${job.title} - ${job.company}`);
      
      // 记录点击前的状态
      const beforeClickDetail = this.getCurrentDetailInfo();
      console.log(`点击前右侧详情:`, beforeClickDetail);
      
      // 先移除所有卡片的active状态
      const allJobCardWraps = document.querySelectorAll('.job-card-wrap');
      console.log(`找到 ${allJobCardWraps.length} 个job-card-wrap元素`);
      allJobCardWraps.forEach((card, index) => {
        const wasActive = card.classList.contains('active');
        card.classList.remove('active');
        if (wasActive) {
          console.log(`移除第${index + 1}个卡片的active状态`);
        }
      });
      
      // 滚动到卡片位置
      jobCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
      await this.sleep(800);
      
      // 找到.job-card-wrap元素（这是真正需要点击的元素）
      const jobCardWrap = jobCard.closest('.job-card-wrap') || jobCard.querySelector('.job-card-wrap');
      if (!jobCardWrap) {
        console.error(`❌ 未找到job-card-wrap元素`);
        throw new Error('未找到job-card-wrap元素');
      }
      
      console.log(`🎯 找到job-card-wrap元素，准备点击`);
      
      // 尝试多种点击方式来触发Boss直聘的事件处理器
      console.log(`尝试方式1: 直接点击job-card-wrap`);
      (jobCardWrap as HTMLElement).click();
      await this.sleep(500);
      
      // 检查是否成功
      let hasActive = jobCardWrap.classList.contains('active');
      console.log(`方式1结果: active=${hasActive}`);
      
      if (!hasActive) {
        console.log(`尝试方式2: 点击内部链接`);
        const linkElement = jobCardWrap.querySelector('a[href*="/job_detail/"]') as HTMLElement;
        if (linkElement) {
          // 阻止默认跳转行为，只触发点击事件
          const clickEvent = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window
          });
          linkElement.dispatchEvent(clickEvent);
          await this.sleep(500);
          
          hasActive = jobCardWrap.classList.contains('active');
          console.log(`方式2结果: active=${hasActive}`);
        }
      }
      
      if (!hasActive) {
        console.log(`尝试方式3: 模拟完整的鼠标事件序列`);
        const events = ['mouseenter', 'mouseover', 'mousedown', 'mouseup', 'click'];
        for (const eventType of events) {
          console.log(`触发${eventType}事件`);
          const event = new MouseEvent(eventType, {
            bubbles: true,
            cancelable: true,
            view: window,
            detail: eventType === 'click' ? 1 : 0
          });
          jobCardWrap.dispatchEvent(event);
          await this.sleep(100);
        }
        
        hasActive = jobCardWrap.classList.contains('active');
        console.log(`方式3结果: active=${hasActive}`);
      }
      
      if (!hasActive) {
        console.log(`尝试方式4: 手动添加active类并触发自定义事件`);
        jobCardWrap.classList.add('active');
        
        // 触发自定义事件，可能Boss直聘监听了这个
        const customEvent = new CustomEvent('jobCardClick', {
          bubbles: true,
          detail: { jobCard: jobCardWrap }
        });
        jobCardWrap.dispatchEvent(customEvent);
        
        hasActive = jobCardWrap.classList.contains('active');
        console.log(`方式4结果: active=${hasActive}`);
      }
      
      console.log(`⏳ 等待右侧详情加载...`);
      // 等待右侧详情加载
      await this.sleep(2000);

      // 第三步：验证右侧详情是否正确更新
      let retryCount = 0;
      let isCorrectCompany = false;
      
      while (retryCount < 3 && !isCorrectCompany) {
        console.log(`\n--- 第${retryCount + 1}次验证详情匹配 ---`);
        
        // 检查job-card-wrap是否有active类
        const hasActiveClass = jobCardWrap.classList.contains('active');
        console.log(`🔍 卡片是否有active类: ${hasActiveClass}`);
        
        // 记录点击后的状态
        const afterClickDetail = this.getCurrentDetailInfo();
        console.log(`点击后右侧详情:`, afterClickDetail);
        
        // 验证右侧详情内容
        isCorrectCompany = await this.verifyCompanyInDetail(job);
        console.log(`🔍 详情内容是否匹配: ${isCorrectCompany}`);
        
        if (!isCorrectCompany || !hasActiveClass) {
          console.log(`❌ 第${retryCount + 1}次验证失败，重新点击`);
          console.log(`原因: active类=${hasActiveClass}, 内容匹配=${isCorrectCompany}`);
          
          // 重新点击 - 使用简单的点击方式
          console.log(`重新触发click事件`);
          (jobCardWrap as HTMLElement).click();
          
          await this.sleep(2000);
          retryCount++;
        } else {
          console.log(`✅ 验证成功！卡片已激活且详情匹配`);
        }
      }

      if (!isCorrectCompany) {
        console.error(`❌ 多次尝试后仍无法匹配正确的公司信息`);
        console.log(`最终右侧详情:`, this.getCurrentDetailInfo());
        this.deliveredJobs.add(job.id);
        this.markJobCardAsProcessed(jobCard);
        throw new Error('无法加载正确的公司详情');
      }

      // 第四步：检查投递状态
      const deliveryStatus = this.checkDeliveryStatus();
      
      if (deliveryStatus === 'already_delivered') {
        console.log(`职位 ${job.title} 已经沟通过，跳过`);
        this.showToast(`${job.title} 已沟通过，跳过`, 'info');
        
        this.markJobCardAsProcessed(jobCard);
        this.deliveredJobs.add(job.id);
        
        const record: DeliveryRecord = {
          id: `delivery_${Date.now()}_${Math.random()}`,
          jobTitle: job.title,
          companyName: job.company,
          salary: job.salary,
          location: job.location,
          detailUrl: job.url,
          deliveryTime: new Date().toISOString(),
          status: 'skipped' as any
        };
        await addDeliveryRecord(record);
        
        return false;
      }
      
      if (deliveryStatus === 'not_available') {
        console.log(`职位 ${job.title} 不可投递`);
        this.showToast(`${job.title} 不可投递，跳过`, 'warning');
        this.markJobCardAsProcessed(jobCard);
        return false;
      }

      // 第五步：查找并点击"立即沟通"按钮
      const deliveryButton = this.findDeliveryButtonInDetail();
      if (!deliveryButton) {
        throw new Error('未找到立即沟通按钮');
      }

      console.log('点击立即沟通按钮...');
      deliveryButton.click();
      
      await this.sleep(2000);
      await this.handleDeliveryConfirmation();
      await this.sleep(1000);

      this.markJobCardAsProcessed(jobCard);
      this.deliveredJobs.add(job.id);
      
      const record: DeliveryRecord = {
        id: `delivery_${Date.now()}_${Math.random()}`,
        jobTitle: job.title,
        companyName: job.company,
        salary: job.salary,
        location: job.location,
        detailUrl: job.url,
        deliveryTime: new Date().toISOString(),
        status: 'success'
      };
      
      await addDeliveryRecord(record);
      this.showToast(`投递成功: ${job.title}`, 'success');
      return true;
      
    } catch (error) {
      console.error('投递失败:', error);
      
      if (jobCard) {
        this.markJobCardAsProcessed(jobCard);
      }
      
      const record: DeliveryRecord = {
        id: `delivery_${Date.now()}_${Math.random()}`,
        jobTitle: job.title,
        companyName: job.company,
        salary: job.salary,
        location: job.location,
        detailUrl: job.url,
        deliveryTime: new Date().toISOString(),
        status: 'failed'
      };
      
      await addDeliveryRecord(record);
      this.showToast(`投递失败: ${job.title}，继续下一个`, 'warning');
      return false;
      
    } finally {
      if (jobCard) {
        jobCard.classList.remove('boss-auto-delivery-highlight');
      }
    }
  }

  // 获取当前右侧详情信息（用于调试）
  private getCurrentDetailInfo(): any {
    const detailContainer = document.querySelector('.job-detail-container');
    if (!detailContainer) {
      return { error: '未找到详情容器' };
    }

    const jobNameElement = detailContainer.querySelector('.job-name');
    const bossInfoElement = detailContainer.querySelector('.boss-info-attr');
    const chatButtonElement = detailContainer.querySelector('.op-btn-chat');

    return {
      jobName: jobNameElement?.textContent?.trim() || '未找到',
      bossInfo: bossInfoElement?.textContent?.trim() || '未找到',
      hasChatButton: !!chatButtonElement,
      chatButtonText: chatButtonElement?.textContent?.trim() || '无按钮'
    };
  }

  // 验证右侧详情是否为正确的公司信息
  private async verifyCompanyInDetail(job: JobInfo): Promise<boolean> {
    const detailContainer = document.querySelector('.job-detail-container');
    if (!detailContainer) {
      console.log('未找到详情容器');
      return false;
    }

    // 查找详情中的职位标题和公司名称
    const detailTitleSelectors = [
      '.job-detail-title',
      '.job-title',
      '.detail-job-name',
      '.job-name',
      'h1'
    ];

    const detailCompanySelectors = [
      '.company-name',
      '.detail-company-name',
      '.company-info .name',
      '.boss-info .name',
      '.company-title'
    ];

    let detailTitle = '';
    let detailCompany = '';

    // 查找职位标题
    for (const selector of detailTitleSelectors) {
      const element = detailContainer.querySelector(selector);
      if (element && element.textContent?.trim()) {
        detailTitle = element.textContent.trim();
        break;
      }
    }

    // 查找公司名称
    for (const selector of detailCompanySelectors) {
      const element = detailContainer.querySelector(selector);
      if (element && element.textContent?.trim()) {
        detailCompany = element.textContent.trim();
        break;
      }
    }

    console.log('详情验证:', {
      目标职位: job.title,
      详情职位: detailTitle,
      目标公司: job.company,
      详情公司: detailCompany
    });

    // 如果找不到详情信息，认为还没加载完成
    if (!detailTitle && !detailCompany) {
      return false;
    }

    // 检查职位标题和公司名称是否匹配（使用更宽松的匹配规则）
    const titleMatch = !detailTitle || detailTitle.includes(job.title) || job.title.includes(detailTitle);
    const companyMatch = !detailCompany || detailCompany.includes(job.company) || job.company.includes(detailCompany);

    return titleMatch && companyMatch;
  }

  // 检查投递状态（在详情页面中检查）
  private checkDeliveryStatus(): 'can_deliver' | 'already_delivered' | 'not_available' {
    const detailContainer = document.querySelector('.job-detail-container');
    if (!detailContainer) {
      console.log('未找到详情容器');
      return 'not_available';
    }

    // 检查按钮文本是否显示已沟通过的状态
    const allButtons = detailContainer.querySelectorAll('button, a');
    for (const button of allButtons) {
      const text = button.textContent?.trim().toLowerCase();
      if (text && (
        text.includes('已沟通') || 
        text.includes('继续沟通') || 
        text.includes('已投递') ||
        text.includes('查看沟通') ||
        text.includes('已联系')
      )) {
        console.log(`按钮文本显示已沟通: ${text}`);
        return 'already_delivered';
      }
    }

    // 检查是否有可用的立即沟通按钮
    const chatButton = detailContainer.querySelector('.op-btn-chat');
    if (chatButton && chatButton.textContent?.includes('立即沟通')) {
      return 'can_deliver';
    }

    // 查找其他可能的沟通按钮
    const communicateButtons = detailContainer.querySelectorAll('button, a');
    for (const button of communicateButtons) {
      const text = button.textContent?.trim();
      if (text && text.includes('立即沟通')) {
        return 'can_deliver';
      }
    }

    // 如果没有找到任何沟通按钮，可能职位已下线
    return 'not_available';
  }

  // 查找职位卡片
  private findJobCard(job: JobInfo): HTMLElement | null {
    const jobCards = document.querySelectorAll('.job-card-wrap');
    
    for (const card of jobCards) {
      const titleElement = card.querySelector('.job-name');
      const companyElement = card.querySelector('.boss-name');
      
      if (titleElement && companyElement) {
        const title = titleElement.textContent?.trim();
        const company = companyElement.textContent?.trim();
        
        if (title === job.title && company === job.company) {
          return card as HTMLElement;
        }
      }
    }
    
    return null;
  }

  // 在详情区域查找投递按钮
  private findDeliveryButtonInDetail(): HTMLElement | null {
    const detailContainer = document.querySelector('.job-detail-container');
    if (!detailContainer) {
      console.log('未找到详情容器');
      return null;
    }

    // 查找"立即沟通"按钮
    const chatButton = detailContainer.querySelector('.op-btn-chat') as HTMLElement;
    if (chatButton && chatButton.textContent?.includes('立即沟通')) {
      return chatButton;
    }

    // 备用选择器 - 查找所有可能的沟通按钮
    const allButtons = detailContainer.querySelectorAll('button, a');
    for (const button of allButtons) {
      const text = button.textContent?.trim();
      if (text && text.includes('立即沟通')) {
        return button as HTMLElement;
      }
    }

    return null;
  }

  // 处理投递确认弹窗
  private async handleDeliveryConfirmation(): Promise<void> {
    await this.sleep(1000);
    
    console.log('检查是否有弹窗需要处理...');
    
    // 首先处理"留在此页"弹窗
    const stayButton = document.querySelector('.greet-boss-footer .cancel-btn') as HTMLElement;
    if (stayButton && stayButton.textContent?.includes('留在此页')) {
      console.log('找到"留在此页"按钮，点击...');
      stayButton.click();
      await this.sleep(1000);
    }
    
    // 查找其他确认按钮
    const confirmSelectors = [
      '.dialog-confirm',
      '.btn-confirm',
      '.modal-footer button[type="submit"]',
      '.sure-btn',
      'button[type="submit"]'
    ];

    for (const selector of confirmSelectors) {
      const confirmBtn = document.querySelector(selector) as HTMLElement;
      if (confirmBtn && confirmBtn.offsetParent !== null) {
        console.log(`找到确认按钮: ${selector}`);
        confirmBtn.click();
        await this.sleep(500);
        break;
      }
    }
    
    // 使用文本内容查找按钮
    const allButtons = document.querySelectorAll('button, a');
    for (const button of allButtons) {
      const text = button.textContent?.trim();
      if (text && (text.includes('确认') || text.includes('发送') || text.includes('继续沟通'))) {
        const htmlButton = button as HTMLElement;
        if (htmlButton.offsetParent !== null) {
          console.log(`通过文本找到按钮: ${text}`);
          htmlButton.click();
          await this.sleep(500);
          break;
        }
      }
    }
  }

  // 滚动到下一页
  private async scrollToNextPage(): Promise<void> {
    const currentScrollTop = window.pageYOffset;
    const documentHeight = document.documentElement.scrollHeight;
    const windowHeight = window.innerHeight;

    // 滚动到页面底部
    window.scrollTo({
      top: documentHeight,
      behavior: 'smooth'
    });

    await this.sleep(2000);

    // 检查是否有新内容加载
    const newDocumentHeight = document.documentElement.scrollHeight;
    if (newDocumentHeight > documentHeight) {
      this.showToast('检测到新内容，继续投递...');
      this.currentJobIndex = 0; // 重置职位索引
      await this.sleep(1000);
      this.processCurrentPage();
    } else {
      this.showToast('已到达页面底部，投递完成', 'success');
      this.stopDelivery();
    }
  }

  // 显示提示消息
  private showToast(message: string, type: 'info' | 'success' | 'warning' | 'error' = 'info') {
    const existingToast = document.querySelector('.boss-auto-delivery-toast');
    if (existingToast) {
      existingToast.remove();
    }

    const toast = document.createElement('div');
    toast.className = 'boss-auto-delivery-toast';
    toast.textContent = message;
    
    // 根据类型设置颜色
    switch (type) {
      case 'success':
        toast.style.background = '#10b981';
        break;
      case 'warning':
        toast.style.background = '#f59e0b';
        break;
      case 'error':
        toast.style.background = '#ef4444';
        break;
      default:
        toast.style.background = '#00D4AA';
    }

    document.body.appendChild(toast);

    setTimeout(() => {
      toast.remove();
    }, 3000);
  }

  // 延时函数
  private sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// 初始化
new BossAutoDelivery();
